package com.cn.wanxi.autoconfig.interceptor;

import com.cn.learn.starter.service.ITimeService;
import com.cn.wanxi.autoconfig.annotation.PermissionCheck;
import com.cn.wanxi.autoconfig.annotation.RequestLog;
import com.cn.wanxi.autoconfig.vo.ResultVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.RuntimeNode;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;

/**
 * @ClassName ExceptionInterceptor
 * @Description 权限拦截器
 * @Author JiJiang
 * @Date 2022/9/14 11:02
 * @Version 1.0
 */
@Log4j2
@Component
public class PermissionInterceptor implements HandlerInterceptor {


    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private ITimeService timeService;


    /**
     * 在执行controller方法前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        StringBuffer requestURL = request.getRequestURL();
        log.info("执行类：{}的方法：{}，时间为：{}，路径为：{}", this.getClass().getName(), "preHandle", timeService.getTimeForYMDHIS(System.currentTimeMillis()), requestURL);

//        Class<?> aClass = handler.getClass();
//        log.info("handler 的类型为：{}", aClass.getName());


        if (handler instanceof HandlerMethod) {
            HandlerMethod tmp = (HandlerMethod) handler;
            //获取到方法上的所有注解
            Annotation[] declaredAnnotations = tmp.getMethod().getDeclaredAnnotations();

            PermissionCheck permissionCheck = null;

            for (Annotation declaredAnnotation : declaredAnnotations) {

                if (declaredAnnotation instanceof PermissionCheck) {
                    permissionCheck = (PermissionCheck) declaredAnnotation;
                    break;
                }
            }

            //如果增强的方法上有权限注解
            if (permissionCheck != null) {

                //如果需要权限的校验
                if (permissionCheck.needCheckToken()) {

                    String token = request.getHeader(permissionCheck.tokenKey());

                    if (Strings.isEmpty(token)) {


                        String result = objectMapper.writeValueAsString(ResultVO.getResultOnlyMsg("no auth"));

                        response.getOutputStream().print(result);
                        return false;
                    }
                }
            }


        }
        return true;
    }


    /**
     * 在执行controller方法后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        log.info("执行类：{}的方法：{}时间为：{}", this.getClass().getName(), "postHandle", timeService.getTimeForYMDHIS(System.currentTimeMillis()));

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("执行类：{}的方法：{}时间为：{}", this.getClass().getName(), "afterCompletion", timeService.getTimeForYMDHIS(System.currentTimeMillis()));

        //异常不为空
        if (ex != null) {
            response.getOutputStream().print("server error!");
        }


    }
}
